package com.tdrc.common.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.tdrc.common.beans.Role;
import com.tdrc.common.service.RoleService;
import com.tdrc.common.util.JsonResult;
import com.tdrc.common.beans.ResultCode;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * @author dpf
 * @version 1.0
 * @date 2020-4-3 15:17
 * @instruction ...
 */
@RestController
@RequestMapping("/role")
public class RoleController extends  BaseController {
    @Resource
    private RoleService roleService;

    @PostMapping("/add")
    public Object add(@RequestBody Role role){
        //检查角色名称的唯一性
        if(ResultCode.ROLE_NAME_NOTE_UNIQUE.getVal()==roleService.checkRoleNameUnique(role.getRoleName())){
            return new JsonResult(ResultCode.ROLE_NAME_NOTE_UNIQUE);
        }
         roleService.addRole(role);
        this.addRoleMenu(role.getRoleId(),role.getMenuIds());
        return new JsonResult(ResultCode.OK);
    }
    @PostMapping("/update")
    public Object update(@RequestBody Role role){
        roleService.updateRole(role);
        roleService.deleteRoleMenuByRoleId(role.getRoleId());
        addRoleMenu(role.getRoleId(),role.getMenuIds());
        return new JsonResult(ResultCode.OK);
    }
    public void addRoleMenu(Integer roleId,String menuIds){
         //先根据roleId删除
        roleService.deleteRoleMenuByRoleId(roleId);
        List<Integer> list=new ArrayList<Integer>();
        if(StringUtil.isNotEmpty(menuIds)) {
            String[] arr=menuIds.split(",");
            for(int i=0,len=arr.length;i<len;i++) {
                list.add(Integer.parseInt(arr[i]));
            }
            roleService.addRoleMenu(roleId, list);
        }

    }
    @DeleteMapping("/delete/{roleId}")
    @Transactional(rollbackFor = Exception.class)
    public Object delete(@PathVariable Integer roleId){
        roleService.deleteRoleMenuByRoleId(roleId);
        roleService.deleteRole(roleId);
        return new JsonResult(ResultCode.OK);
    }
    @GetMapping("/list")
    public Object list(Integer page,Integer pageSize,String roleName){
        PageHelper.startPage(page, pageSize);
                   //.setOrderBy("roleId desc");

        List<Role> logData = roleService.listRole(roleName);
        PageInfo<Role> pageInfo = new PageInfo<Role>(logData);
        return new JsonResult(ResultCode.OK,pageInfo.getList(),pageInfo.getTotal());
    }
    @GetMapping("/getRoleMenuByRoleId")
    public Object getRoleMenuByRoleId(Integer roleId){
        return new JsonResult(ResultCode.OK,roleService.getRoleMenuByRoleId(roleId));
    }


}
